package com.lanou3g.zjl.chating.home.friends;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseActivity;
import com.lanou3g.zjl.chating.home.personal_center.CircleImageView;
import com.lanou3g.zjl.chating.utils.GetUserAvatarHelper;
import com.lanou3g.zjl.chating.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by dllo on 15/11/26.
 */
public class InvitFriendsIntoGroupActivity extends BaseActivity {
    //黑名单
    private List<String> blackList;
    //该集合存储好友
    private List<String> friendsNane;
    private List<FriendsInfo> data;
    private Handler handler;
    private String groupId;
    private EMGroup group;//群对象
    private boolean isOwner;//是否是群主
    private boolean isPublic;//是否公开
    private boolean isAllowInvit;//是否允许群成员邀请
    private List<String> invitWho;//保存邀请了哪些好友
    private List<String> groupBlackList;//群黑名单
    private String[] newmembers;
    @Bind(R.id.toInvitFriendsList)
    ListView toInvitFriendsList;

    @Override
    protected int getLayout() {
        return R.layout.invit_togroup_friendslist;
    }

    @Override
    protected void initData() {
        invitWho = new ArrayList<>();
        groupId = getIntent().getStringExtra("ID");
        getAsynk();
        //获取群信息
        getGroupInfo(groupId);
    }

    @OnClick(R.id.finishAddFriendTogrouop)
    void finishAddFriendTogrouop() {
        finish();
    }

    //保存邀请的好友
    @OnClick(R.id.saveInvit)
    void saveInvit() {
        if (!(invitWho.size() == 0)) {
            //将集合装换为数组
            newmembers = new String[invitWho.size()];
            for (int i = 0; i < invitWho.size(); i++) {
                newmembers[i] = invitWho.get(i);
            }
            if (isOwner) {
                ownerInvit();
            } else {
                if (isAllowInvit && !isPublic) {
                    membersInvit();
                }
            }
            for (String s : invitWho) {
                Log.i("lanou", s + "看看我都邀请了谁");
            }
            //保存一次清空一次
            invitWho.clear();
        } else {
            Toast.makeText(InvitFriendsIntoGroupActivity.this, "请选择好友", Toast.LENGTH_SHORT).show();
        }
    }

    //获取子线程消息
    private void getAsynk() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case 1:
                        toInvitFriendsList.setAdapter(new MyAdapter());
                        break;
                    case 2:
                        //初始化黑名单
                        getBlackList();
                        break;
                    case 3:
                        //邀请成功
                        Toast.makeText(InvitFriendsIntoGroupActivity.this, "好友已成功加入群聊", Toast.LENGTH_SHORT).show();
                        getGroupInfo(groupId);
                        break;
                    case 4:
                        //初始化好友列表
                        initFriends();
                        break;
                }
                return false;
            }
        });
    }

    //群主拉人进群
    private void ownerInvit() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    EMGroupManager.getInstance().addUsersToGroup(groupId, newmembers);
                    handler.sendEmptyMessage(3);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //群成员拉人进群
    private void membersInvit() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMGroupManager.getInstance().inviteUser(groupId, newmembers, null);
                    handler.sendEmptyMessage(3);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //根据群id去服务器得到该群的详细信息
    private void getGroupInfo(final String groupId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    group = EMGroupManager.getInstance().getGroupFromServer(groupId);

                    if (group != null) {
                        if (group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
                            isOwner = true;
                        } else {
                            isOwner = false;
                        }
                        if (group.isPublic()) {
                            isPublic = true;
                        } else {
                            isPublic = false;
                        }
                        if (group.isAllowInvites()) {
                            isAllowInvit = true;
                        } else {
                            isAllowInvit = false;
                        }
                        handler.sendEmptyMessage(2);
                    }
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //初始化好友列表
    private void initFriends() {
        data = new ArrayList<>();
        //初始化黑名单
        blackList = EMContactManager.getInstance().getBlackListUsernames();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    friendsNane = EMContactManager.getInstance().getContactUserNames();//需异步执行
                    if (friendsNane != null) {
                        for (String s : friendsNane) {
                            if (!blackList.contains(s) && !group.getMembers().contains(s) && !groupBlackList.contains(s)) {
                                FriendsInfo info = new FriendsInfo();
                                info.setName(s);
                                data.add(info);
                            }
                        }
                        handler.sendEmptyMessage(1);
                    }
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //获取群黑名单列表
    private void getBlackList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    groupBlackList = EMGroupManager.getInstance().getBlockedUsers(groupId);
                    handler.sendEmptyMessage(4);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data != null && data.size() > 0 ? data.size() : 0;
        }

        @Override
        public FriendsInfo getItem(int i) {
            return data != null && data.size() > 0 ? data.get(i) : null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder = null;
            final FriendsInfo info = getItem(i);
            if (view == null) {
                view = LayoutInflater.from(InvitFriendsIntoGroupActivity.this).inflate(R.layout.toinvit_friendslist_item, null);
                holder = new ViewHolder(view);
                holder.isInvitToGroup = (AnimateCheckBox) view.findViewById(R.id.isInvitToGroup);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.toInvitName.setText(info.getName());
            //设置checkbox选中时的颜色
            holder.isInvitToGroup.setCircleColor(Color.GREEN);
            //在选择好友时讲数据保存起来
            holder.isInvitToGroup.setOnCheckedChangeListener(new AnimateCheckBox.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(View buttonView, boolean isChecked) {
                    if (invitWho.contains(info.getName())) {
                        invitWho.remove(info.getName());
                    } else {
                        invitWho.add(info.getName());
                    }
                }
            });
            //加载头像
            Handler handler= new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message message) {
                    String url = (String) message.obj;
                    data.get(i).setAvatar(url);
                    notifyDataSetChanged();
                    return false;
                }
            });

            if (data.get(i).getAvatar() != null && data.get(i).getAvatar().length() > 0){
                VolleySingleton.getInstance(viewGroup.getContext()).getPic(data.get(i).getAvatar(), holder.toinvitPic);//前台进行头像设置
            }
            else
            {
                holder.toinvitPic.setImageResource(R.mipmap.default_head);
            }
            GetUserAvatarHelper helper = new GetUserAvatarHelper(InvitFriendsIntoGroupActivity.this,handler);
            helper.execute(info.getName());
            return view;
        }

        class ViewHolder {
            AnimateCheckBox isInvitToGroup;
            @Bind(R.id.toinvitPic)
            CircleImageView toinvitPic;
            @Bind(R.id.toInvitName)
            TextView toInvitName;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }
}
